/**
 * 
 */
package org.mspring.codegen.engine.handler;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;

import org.mspring.codegen.engine.entity.BaseEntity;
import org.mspring.codegen.engine.utils.TemplateUtils;
import org.mspring.platform.utils.FreemarkerUtils;
import org.mspring.platform.utils.StringUtils;

import freemarker.template.Template;

/**
 * 
 * @author Gao Youbo
 * @since 2013-6-18
 */
public abstract class AbstractHandler {

    public abstract void process(BaseEntity entity);

    public void process(BaseEntity entity, Template template) {
        // TODO Auto-generated method stub
        Map<Object, Object> model = new HashMap<Object, Object>();
        model.put("entity", entity);

        String result = FreemarkerUtils.render(template, model);
        write(entity, result);
    }

    public void write(BaseEntity entity, String result) {
        String[] folders = StringUtils.split(entity.getPkg(), ".");
        String path = TemplateUtils.DEFAULT_FOLDER + "/";
        for (String f : folders) {
            path += f + "/";
        }
        path += entity.getName() + ".java";

        try {
            File file = new File(path);
            file.getParentFile().mkdirs();

            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            out.write(result);
            out.close();

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}
